/**
 * API请求工具
 */

// API基础URL
const BASE_URL = 'http://localhost:10001/api/v1/drivionExe'

/**
 * 发送HTTP请求
 * @param {string} url - 请求URL
 * @param {object} options - 请求选项
 * @returns {Promise<any>} 响应数据
 */
async function request(url, options = {}) {
  const defaultOptions = {
    credentials: 'include', // 允许携带Cookie
    headers: {
      'Content-Type': 'application/json',
      ...options.headers
    }
  }

  const finalOptions = { ...defaultOptions, ...options }
  
  try {
    const response = await fetch(`${BASE_URL}${url}`, finalOptions)
    const data = await response.json()
    
    // 检查业务状态码
    if (data.code !== 200) {
      throw new Error(data.message || '请求失败')
    }
    
    return data
  } catch (error) {
    console.error('Request error:', error)
    throw error
  }
}

/**
 * GET请求
 */
export function get(url, params = {}) {
  const queryString = new URLSearchParams(params).toString()
  const fullUrl = queryString ? `${url}?${queryString}` : url
  
  return request(fullUrl, {
    method: 'GET'
  })
}

/**
 * POST请求
 */
export function post(url, data = {}) {
  return request(url, {
    method: 'POST',
    body: JSON.stringify(data)
  })
}

/**
 * PUT请求
 */
export function put(url, data = {}) {
  return request(url, {
    method: 'PUT',
    body: JSON.stringify(data)
  })
}

/**
 * DELETE请求
 */
export function del(url) {
  return request(url, {
    method: 'DELETE'
  })
}

export default {
  get,
  post,
  put,
  delete: del
}
